/*
Filename: UCBuyTickets.java
Precondition:Click show ticket all or user login success.
Post-condition: buy ticket success.
Main success Scenario:
1. check ticket left.
2. if user buy more give discount.
2a. Extensions: no ticket user select:
1. System display “ticket sale out “message
 */

package ucm;

/**
 *
 * @author Mark
 */
import model.InputModel;
import model.DatabaseModel;
import view.ShowTicket;

import javax.swing.*;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;

public class UCBuyTickets implements UCController {

    private InputModel inputmodel;
    int j;
    int disco;

    public UCBuyTickets() {
        inputmodel = new InputModel("", "", "", "", "", "", "", "", "");
    }

    public UCBuyTickets(InputModel inputmodel) {
        // System retrieves inputs.
        this.inputmodel = inputmodel;
    }

    public UCBuyTickets(ShowTicket ShowTicket) {
        this.inputmodel = ShowTicket.getinputModel();
    }

    public boolean run() {
        boolean registeredSuccessful = false;
            if (Ticketleft()){
                if (buyTicket()) {
                    if(giveDiscount()){

                    JOptionPane.showMessageDialog(new JFrame(),
                            "Buy tickets Successfully Your will get "+disco+"% discount!",
                            "Success",
                            JOptionPane.INFORMATION_MESSAGE);
                       registeredSuccessful = true;
                      new ucm.UCDispalyTicketsaler();
                    }else{
                    JOptionPane.showMessageDialog(new JFrame(),
                            "Buy tickets Successfully!",
                            "Success",
                            JOptionPane.INFORMATION_MESSAGE);
                       registeredSuccessful = true;
                      new ucm.UCDispalyTicketsaler();
                    }
                } else {
                    JOptionPane.showMessageDialog(new JFrame(),
                            "unknow error",
                            "Error Message",
                            JOptionPane.ERROR_MESSAGE);
                }
            } else {
                JOptionPane.showMessageDialog(new JFrame(),
                        "we just have "+j+" tickets left",
                        "Error Message",
                        JOptionPane.ERROR_MESSAGE);
            }

        return registeredSuccessful;
    }

    public void run(InputModel inputmodel) {
        this.inputmodel = inputmodel;
        run();
    }

private boolean isNumeric() {
        int begin = 0;
        String str = inputmodel.getUserInput();
        boolean once = true;
        if (str == null || str.trim().equals("")) {
            return false;
        }
        str = str.trim();
        if (str.startsWith("+") || str.startsWith("-")) {
            if (str.length() == 1) {
                // "+" "-"
                return false;
            }
            begin = 1;
        }
        for (int i = begin; i < str.length(); i++) {
            if (!Character.isDigit(str.charAt(i))) {
                if (str.charAt(i) == '.' && once) {
                    // '.' can only once
                    once = false;
                }
                else {
                    return false;
                }
            }
        }
        if (str.length() == (begin + 1) && !once) {
            // "." "+." "-."
            return false;
        }
        return true;
    }

private boolean isNumeric2() {
        int begin = 0;
        String str = inputmodel.getticketcount();
        boolean once = true;
        if (str == null || str.trim().equals("")) {
            return false;
        }
        str = str.trim();
        if (str.startsWith("+") || str.startsWith("-")) {
            if (str.length() == 1) {
                // "+" "-"
                return false;
            }
            begin = 1;
        }
        for (int i = begin; i < str.length(); i++) {
            if (!Character.isDigit(str.charAt(i))) {
                if (str.charAt(i) == '.' && once) {
                    // '.' can only once
                    once = false;
                }
                else {
                    return false;
                }
            }
        }
        if (str.length() == (begin + 1) && !once) {
            // "." "+." "-."
            return false;
        }
        return true;
    }
private boolean isNumer() {
    if(isNumeric() && isNumeric2()){
    return false;
    }

    return true;
}

    private boolean Ticketleft() {
        boolean unique = false;
        String UserInput = inputmodel.getUserInput();
        String ticketcount = inputmodel.getticketcount();


        try {
            int i = Integer.valueOf(ticketcount).intValue();
            Connection con = DatabaseModel.getInstance().getConnection();
            Statement stmt = con.createStatement(ResultSet.CONCUR_UPDATABLE,ResultSet.CONCUR_UPDATABLE);
            ResultSet res = stmt.executeQuery("select * from tickets where id ="+UserInput);
             System.out.println(res.next());
              System.out.println(res.getInt("tseats"));
             int  a = res.getInt("tseats");
             System.out.println(a);
              ResultSet res2 = stmt.executeQuery("SELECT SUM(BSEATS) FROM buytickets WHERE BID ="+UserInput);
              System.out.println(res2.next());
              int  b = res2.getInt("SUM(BSEATS)");
              System.out.println(b);
               j = a-b;


          if(j >= i){
              unique =true;
          }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return unique;

    }
        private boolean giveDiscount(){
          boolean discount = false;
          String ticketcount = inputmodel.getticketcount();


          try {
            int i = Integer.valueOf(ticketcount).intValue();
            Connection con = DatabaseModel.getInstance().getConnection();
            Statement stmt = con.createStatement(ResultSet.CONCUR_UPDATABLE,ResultSet.CONCUR_UPDATABLE);
            ResultSet res = stmt.executeQuery("select * from discount where did > 0");
             System.out.println(res.next());
             int  a = res.getInt("dticketno");
             disco =  res.getInt("dcount");

          if(i >= a){
              discount =true;
          }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return discount;
        }


    private boolean buyTicket(){
        boolean register = false;
        String UserInput = inputmodel.getUserInput();
        String ticketcount = inputmodel.getticketcount();
         int tid,bprice,bseats;
        String bflight,bfrom,barrive;

        DatabaseModel dbModel = DatabaseModel.getInstance();

        Connection con = dbModel.getConnection();
        try {
            Statement stmt = con.createStatement(ResultSet.CONCUR_UPDATABLE,
                    ResultSet.CONCUR_UPDATABLE);
            ResultSet res = stmt.executeQuery("select * from tickets where " + "id ="+UserInput+"");
            System.out.println("select * from tickets where " + "id ="+UserInput+"");
             System.out.println(res.next());
           tid = res.getInt("ID");
           bflight = res.getString("TFLIGHT");
           bfrom = res.getString("TFROM");
           barrive = res.getString("TARRIVE");
           bprice = res.getInt("TPRICE");
           bseats = res.getInt("TSEATS");
            ResultSet resw = stmt.executeQuery("SELECT * FROM tempusers where uid > 0");
             System.out.println("SELECT * FROM tempusers where uid > 0");
             System.out.println(resw.next());
             int uid =resw.getInt("uid");
             String uname =resw.getString("uname");
             stmt.executeUpdate("INSERT INTO buytickets(`BID`, `BFLIGHT`, `BFROM`, `BARRIVE`, `BPRICE`, `BSEATS`, `UID`, `UNAME`)VALUES(" + tid +", '"+ bflight + "','"+bfrom+ "','"+barrive+ "',"+bprice+ ","+ticketcount+ ","+uid+",'"+uname+"')");


            //database.
            register = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return register;
    }
}